package com.maiyawx.mall.service;

import com.alibaba.fastjson.JSONObject;
import com.maiyawx.mall.entity.Users;
import com.maiyawx.mall.enums.CommonEnum;
import com.maiyawx.mall.exception.CommonException;
import com.maiyawx.mall.mapper.UsersMapper;
import com.maiyawx.mall.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

/**
 * 用户服务
 */
@Service
public class UsersService {

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 添加用户或更新用户
     *
     * @param userInfo
     * @param sessionKeyData
     * @param request
     * @return
     */
    public Users addOrUpdate(JSONObject userInfo, JSONObject sessionKeyData, HttpServletRequest request)
    {
        Users users = new Users();
        users.setAppid(userInfo.getJSONObject("watermark").getString("appid"));
        users.setOpenid(userInfo.getString("openId"));
        users.setNickname(userInfo.getString("nickName"));
        users.setAvatarUrl(userInfo.getString("avatarUrl"));
        users.setSessionKey(sessionKeyData.getString("session_key"));
        users.setGender(userInfo.getBoolean("gender"));
        users.setCity(userInfo.getString("city"));
        users.setProvince(userInfo.getString("province"));
        users.setCountry(userInfo.getString("country"));
        users.setLanguage(userInfo.getString("language"));
        users.setLastLoginTime(new Timestamp(userInfo.getJSONObject("watermark").getLong("timestamp") * 1000));
        users.setLastLoginIp(IpUtil.getIpAddr(request));
        users.setRemark("");
        Users users1 = selectByOpenId(userInfo.getString("openId"));
        Integer result;
        if (users1 != null) {
            users.setId(users1.getId());
            result = updateByPrimaryKey(users);
        } else {
            result = usersMapper.insert(users);
            if (!result.equals(0)) {
                users.setId(result);
            } else {
                throw new CommonException(CommonEnum.ADD_ERROR);
            }
        }
        return users;
    }

    /**
     * 根据open id 查询
     * @param openid
     * @return
     */
    public Users selectByOpenId(String openid)
    {
        return usersMapper.selectByOpenId(openid);
    }

    /**
     * 更新用户信息
     * @param users
     * @return
     */
    public Integer updateByPrimaryKey(Users users)
    {
        return usersMapper.updateByPrimaryKey(users);
    }
}
